package com.evaluation.controller;

import com.evaluation.common.Result;
import com.evaluation.entity.CpType;
import com.evaluation.service.CpTypeService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测评类型管理Controller
 */
@RestController
@RequestMapping("/api/admin")
public class AdminEvaluationTypeController {

    @Autowired
    private CpTypeService cpTypeService;

    /**
     * 获取测评类型列表
     */
    @GetMapping("/evaluation-types")
    public Result<Map<String, Object>> getEvaluationTypes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String typeName) {

        try {
            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CpType> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

            if (typeName != null && !typeName.trim().isEmpty()) {
                queryWrapper.like("LXMC", typeName.trim());
            }

            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<CpType> pageParam =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<CpType> result =
                    cpTypeService.page(pageParam, queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", result.getCurrent());
            data.put("size", result.getSize());

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测评类型列表失败");
        }
    }

    /**
     * 新增测评类型
     */
    @PostMapping("/evaluation-types")
    public Result<String> addEvaluationType(@RequestBody CpType cpType) {
        try {
            // 检查类型名称是否已存在
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CpType> queryWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("LXMC", cpType.getLxmc());
            CpType existingType = cpTypeService.getOne(queryWrapper);
            if (existingType != null) {
                return Result.error("测评类型名称已存在");
            }
            
            // 如果编号为空，自动生成编号
            if (cpType.getLxbh() == null || cpType.getLxbh().trim().isEmpty()) {
                cpType.setLxbh(generateCpTypeId());
            } else {
                // 检查编号是否已存在
                CpType existingTypeById = cpTypeService.getById(cpType.getLxbh());
                if (existingTypeById != null) {
                    return Result.error("测评类型编号已存在");
                }
            }
            
            boolean success = cpTypeService.save(cpType);
            if (success) {
                return Result.success("新增测评类型成功");
            } else {
                return Result.error("新增测评类型失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增测评类型失败：" + e.getMessage());
        }
    }

    /**
     * 根据测评类型编号查询测评类型详情
     */
    @GetMapping("/evaluation-types/{lxbh}")
    public Result<CpType> getEvaluationTypeDetail(@PathVariable String lxbh) {
        try {
            CpType cpType = cpTypeService.getById(lxbh);
            if (cpType == null) {
                return Result.error("测评类型不存在");
            }
            return Result.success(cpType);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询测评类型详情失败");
        }
    }

    /**
     * 更新测评类型
     */
    @PutMapping("/evaluation-types/{lxbh}")
    public Result<String> updateEvaluationType(@PathVariable String lxbh, @RequestBody CpType cpType) {
        try {
            cpType.setLxbh(lxbh);
            boolean success = cpTypeService.updateById(cpType);
            if (success) {
                return Result.success("更新测评类型成功");
            } else {
                return Result.error("更新测评类型失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新测评类型失败");
        }
    }

    /**
     * 删除测评类型
     */
    @DeleteMapping("/evaluation-types/{lxbh}")
    public Result<String> deleteEvaluationType(@PathVariable String lxbh) {
        try {
            boolean success = cpTypeService.removeById(lxbh);
            if (success) {
                return Result.success("删除测评类型成功");
            } else {
                return Result.error("删除测评类型失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除测评类型失败");
        }
    }

    /**
     * 导入测评类型
     */
    @PostMapping("/evaluation-types/import")
    public Result<Map<String, Object>> importEvaluationTypes(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 使用ExcelUtil读取Excel文件
            List<CpType> dataList = ExcelUtil.readExcel(file, CpType.class);

            int successCount = 0;
            int errorCount = 0;

            for (CpType cpType : dataList) {
                try {
                    // 设置默认值
                    if (cpType.getLxbh() == null || cpType.getLxbh().trim().isEmpty()) {
                        cpType.setLxbh(generateCpTypeId());
                    }

                    cpTypeService.save(cpType);
                    successCount++;
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("total", dataList.size());
            result.put("success", successCount);
            result.put("error", errorCount);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入测评类型失败：" + e.getMessage());
        }
    }

    /**
     * 导出测评类型
     */
    @GetMapping("/evaluation-types/export")
    public void exportEvaluationTypes(HttpServletResponse response) {
        try {
            List<CpType> list = cpTypeService.list();
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (CpType cpType : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("测评类型编号", cpType.getLxbh());
                map.put("测评类型名称", cpType.getLxmc());

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "测评类型数据", exportData);
            } else {
                // 创建空Excel
                exportData.add(new HashMap<String, Object>() {{
                    put("测评类型编号", "");
                    put("测评类型名称", "");
                }});
                ExcelUtil.exportExcel(response, "测评类型数据", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String generateCpTypeId() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CpType> queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.orderByDesc("LXBH").last("LIMIT 1");
        CpType maxRecord = cpTypeService.getOne(queryWrapper);
        if (maxRecord != null && maxRecord.getLxbh() != null) {
            try {
                int maxId = Integer.parseInt(maxRecord.getLxbh());
                return String.valueOf(maxId + 1);
            } catch (NumberFormatException e) {
                return "1";
            }
        }
        return "1";
    }
}
